package com.diy.sigmund.diycommon.test.controller.redis;

import com.diy.sigmund.diycommon.entity.ResultMsg;
import com.diy.sigmund.diycommon.entity.constant.LockConstant;
import com.diy.sigmund.diycommon.middleware.cache.redis.RedisDistributedLock;
import com.diy.sigmund.diycommon.middleware.cache.redis.RedisService;
import com.diy.sigmund.diycommon.util.seq.SeqUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author ylm-sigmund
 * @since 2021/8/17 12:05
 */
@RestController
@RequestMapping("/redisDistributedLock")
public class RedisDistributedLockController {

    @Autowired
    private RedisDistributedLock redisDistributedLock;
    @Autowired
    private RedisService redisService;

    @PostMapping("/testReleaseLock")
    public ResultMsg testReleaseLock() throws InterruptedException {
        String requestId = SeqUtil.getRequestId();
        redisDistributedLock.releaseLock(null, null);
        String str = null;
        // redisService.del(str); // non null key required
        List<String> list = new ArrayList<>();
        list.add(null);
        // redisService.del(list); // non null key required
        return ResultMsg.success();
    }

    @PostMapping("/testRedisDistributedLock")
    public ResultMsg testRedisDistributedLock() throws InterruptedException {
        String requestId = SeqUtil.getRequestId();
        redisDistributedLock.tryLock(LockConstant.TEST_LOCK, requestId, 10);
        TimeUnit.SECONDS.sleep(5);
        redisDistributedLock.releaseLock(LockConstant.TEST_LOCK, requestId);
        return ResultMsg.success();
    }

    @PostMapping("/testTrySpinLock")
    public ResultMsg testTrySpinLock() throws InterruptedException {
        String requestId = SeqUtil.getRequestId();
        redisDistributedLock.trySpinLock(LockConstant.TEST_LOCK, requestId, 10, 1000);
        TimeUnit.SECONDS.sleep(5);
        redisDistributedLock.releaseLock(LockConstant.TEST_LOCK, requestId);
        return ResultMsg.success();
    }
}
